package com.yksj.healthtalk.ui.news;

import java.util.HashMap;
import java.util.Random;

import org.apache.commons.lang.math.NumberUtils;
import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshMultiColumnListView;
import org.json.JSONException;
import org.staggered.lib.MultiColumnListView;
import org.staggered.lib.internal.StaggerAdapterView;
import org.staggered.lib.internal.StaggerAdapterView.OnItemClickListener;
import org.universalimageloader.core.DefaultConfigurationFactory;
import org.universalimageloader.core.DisplayImageOptions;
import org.universalimageloader.core.ImageLoader;
import org.universalimageloader.core.assist.FailReason;
import org.universalimageloader.core.assist.ImageLoadingListener;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.FileUtils;
import com.yksj.healthtalk.utils.SharePreUtils;

/**
 * 
 * 新闻内容列表
 * 
 * @author zhao
 * 
 */
public class NewsListFragment extends Fragment implements OnItemClickListener {
	public String type;
	private MultiColumnListView mColumnListView;
	private PullToRefreshMultiColumnListView mToRefreshMultiColumnListView;
	private DisplayImageOptions mDisplayImageOptions_One,
			mDisplayImageOptions_Two;
	private ImageLoader mImageLoader;
	private NewsAdapter adapter;
//	private int pageSize = 25;
	private float mWidthSize;
	private HashMap<String, String> mReadedNewsMap;
	private int defaultFristImageId;
	private int defaultSecImageId;
	// private HashMap<Integer, Bitmap> defaultImageId;
	private String title;

	Bitmap mDefaultBitmap1;
	Bitmap mDefaultBitmap2;
	Bitmap mDefaultNullURLBitmap;// 当路径不为null时
	PagerRreponseHandler pagerHandler;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		type = getArguments().getString("type");
		title = getArguments().getString("title");
		mImageLoader = ImageLoader.getInstance();
		mReadedNewsMap = FileUtils.fatchReadedNews();
		// defaultImageId = new HashMap<Integer, Bitmap>();

		defaultFristImageId = getArguments().getInt("one", 0);
		defaultSecImageId = getArguments().getInt("two", 1);

		mDisplayImageOptions_One = DefaultConfigurationFactory.createNewSDisplayImageOptions(getActivity(),R.drawable.waterfall_default);

		mDisplayImageOptions_Two = DefaultConfigurationFactory.createNewSDisplayImageOptions(getActivity(),R.drawable.waterfall_default);
		
		pagerHandler = new PagerRreponseHandler();
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.news_list_layout, null);
		mDefaultBitmap1 = BitmapUtils.decodeSampledBitmapFromResource(getResources(), defaultFristImageId, 500, 500);
		mDefaultBitmap2 = BitmapUtils.decodeSampledBitmapFromResource(getResources(), defaultSecImageId, 500, 500);
		mDefaultNullURLBitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.waterfall_default, 500, 500);
		mToRefreshMultiColumnListView = (PullToRefreshMultiColumnListView) view.findViewById(android.R.id.list);
		mColumnListView = mToRefreshMultiColumnListView.getRefreshableView();
		mColumnListView.setOnItemClickListener(this);
		mToRefreshMultiColumnListView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<MultiColumnListView>() {
					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<MultiColumnListView> refreshView) {
						doQueryNewsList(-1);
					}
					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<MultiColumnListView> refreshView) {
						doQueryNewsList(1);
					}
				});
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (savedInstanceState != null) {
			adapter = new NewsAdapter(getActivity());
			String list = savedInstanceState.getString("list");
			try {
				adapter.onChangeData(pagerHandler.jsonArray);
			} catch (com.alibaba.fastjson.JSONException e) {
				e.printStackTrace();
			}
		} else {
			if (adapter == null) {
				DisplayMetrics metrics = new DisplayMetrics();
				getActivity().getWindowManager().getDefaultDisplay()
						.getMetrics(metrics);
				int numer = mColumnListView.getColumnNumber();
				mWidthSize = (float) metrics.widthPixels / numer;
				adapter = new NewsAdapter(getActivity());
				mToRefreshMultiColumnListView.setRefreshing();
				doQueryNewsList(-1);
			}
		}
		
		TextView view = new TextView(getActivity());
		view.setGravity(Gravity.CENTER);
		view.setText("暂无新闻");
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mToRefreshMultiColumnListView.setRefreshing();
				doQueryNewsList(-1);
			}
		});
		mToRefreshMultiColumnListView.setEmptyView(view);
		mToRefreshMultiColumnListView.setAdapter(adapter);
		
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("list", adapter.mArray.toString());
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (mDefaultBitmap1 != null && !mDefaultBitmap1.isRecycled()) {
			mDefaultBitmap1.recycle();
			mDefaultBitmap1 = null;
		}
		if (mDefaultBitmap2 != null && !mDefaultBitmap2.isRecycled()) {
			mDefaultBitmap2.recycle();
			mDefaultBitmap2 = null;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		FileUtils.updateReadedNewIds(mReadedNewsMap);
	}

	@Override
	public void onItemClick(StaggerAdapterView<?> parent, View view,
			int position, long id) {
		String newsId = adapter.getNewsId(position);
		mReadedNewsMap.put(newsId, newsId);
		TextView findViewById = (TextView) view.findViewById(R.id.newsTitleTxt);
		findViewById.setTextColor(getResources().getColor(
				R.color.news_readed_color));
		Intent intent = new Intent(getActivity(), NewsContentActivity.class);
		intent.putExtra("newsId", newsId);
		// if (defaultImageId.containsKey(position)) {
		// intent.putExtra("defaultImageId", defaultImageId.get(position));
		// } else {
		// intent.putExtra("defaultImageId", 0);
		// }
		intent.putExtra("title", title);
		startActivity(intent);
	}

	public String getLastNewsId() {
		if (adapter != null && adapter.getCount() != 0) {
			return adapter.getNewsId(0);
		}
		return null;
	}

	/**
	 * 
	 * 查询新闻列表
	 * 
	 * @param pullType
	 *            刷新方向
	 * 
	 */
	private void doQueryNewsList(int pullType) {
		if (pullType == -1) {// 下拉刷新
			pagerHandler.onRefresh();
		} else {// 上拉更多
			pagerHandler.nextPage();
		}
	}
	
	class PagerRreponseHandler extends ObjectHttpResponseHandler{
		private final int pageSize = 25;//页数
		private int pageNum = 1;//每页条数
		private int pulltype = 0; //刷新状态
		final JSONArray jsonArray  = new JSONArray();
		/**
		 * 下一页
		 */
		public void nextPage(){
			pulltype = 1;
			HttpRestClient.doHttpQueryNewsList(type, String.valueOf(pageNum),String.valueOf(pageSize), this);
		}
		/**
		 * 刷新
		 */
		public void onRefresh(){
			pulltype = 0;
			pageNum = 1;
			jsonArray.clear();
			HttpRestClient.doHttpQueryNewsList(type,String.valueOf(pageNum), String.valueOf(pageSize), this);
		}
		
		@Override
		public Object onParseResponse(String content) {
			try {
				Object object = JSON.parse(content);
				if (object instanceof JSONObject) {
					JSONArray jsonArray = ((JSONObject) object)
							.getJSONArray("PARAMETER2");
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						if (jsonObject.containsKey("PIC_W")) {
							int width = jsonObject.getIntValue("PIC_W");
							int heigth = jsonObject.getIntValue("PIC_H");
							float scale = mWidthSize / width;
							heigth = (int) (heigth * scale);
							jsonObject.put("PIC_W", (int) mWidthSize);
							jsonObject.put("PIC_H", heigth);
						} else {
							jsonObject.put("PIC_W", (int) mWidthSize);
							jsonObject.put("PIC_H", (int) mWidthSize);
						}
					}
					SharePreUtils.saveNewsReadedId(((JSONObject) object).getString("PARAMETER3"));
					return jsonArray;
				}
			} catch (com.alibaba.fastjson.JSONException e) {
			}
			return null;
		}
		@Override
		public void onSuccess(int statusCode, Object response) {
			super.onSuccess(statusCode, response);
			if(response != null){
				JSONArray array = (JSONArray)response;
				jsonArray.addAll(array);
				if(array.size()  !=  0) ++pageNum;
				adapter.onChangeData(jsonArray);
			}
		}
		@Override
		public void onFinish() {
			super.onFinish();
			mToRefreshMultiColumnListView.onRefreshComplete();
		}
	}

	class NewsAdapter extends BaseAdapter {
		final LayoutInflater layoutInflater;
		JSONArray mArray = new JSONArray();
		Random random = new Random();

		public NewsAdapter(Context context) {
			this.layoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * 获得新闻id
		 * 
		 * @param position
		 * @return
		 */
		public String getNewsId(int position) {
			JSONObject jsonObject = getItem(position);
			String newsId = jsonObject.getString("MENUCODE");
			return newsId;
		}

		public void onChangeData(JSONArray array) {
			mArray.clear();
			mArray.addAll(array);
			this.notifyDataSetChanged();
		}

		private String getTitleName(JSONObject jsonObject) throws JSONException {
			return jsonObject.getString("MENUNAME");
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			final JSONObject jsonObject = (JSONObject) getItem(position);
			final ViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(
						R.layout.news_list_item_layout, parent, false);
				ImageView imageView = (ImageView) convertView
						.findViewById(R.id.newsImage);
				TextView textView = (TextView) convertView
						.findViewById(R.id.newsTitleTxt);
				holder = new ViewHolder();
				holder.imageView = imageView;
				holder.textView = textView;
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			try {
				if (mReadedNewsMap.containsKey(getNewsId(position)))
					holder.textView.setTextColor(getResources().getColor(
							R.color.news_readed_color));
				else
					holder.textView.setTextColor(Color.WHITE);

				holder.textView.setText(getTitleName(jsonObject));
				// setColor(holder.textView,position);
				LayoutParams params = holder.imageView.getLayoutParams();
				params.width = jsonObject.getIntValue("PIC_W");
				params.height = jsonObject.getIntValue("PIC_H");
				holder.imageView.setLayoutParams(params);
				if (jsonObject.containsKey("MENUPIC")) {
					String url = jsonObject.getString("MENUPIC");
					int nextInt = random.nextInt(2);
					if (url == null && nextInt == 0) {
						holder.imageView.setImageBitmap(mDefaultBitmap1);
					} else if (url == null && nextInt == 1) {
						holder.imageView.setImageBitmap(mDefaultBitmap2);
					} else if (nextInt == 0) {
						mImageLoader.displayImage(url, holder.imageView,
								mDisplayImageOptions_Two,
								new ImageLoadingListener() {
									@Override
									public void onLoadingStarted() {
									}

									@Override
									public void onLoadingFailed(
											FailReason failReason) {
										holder.imageView.setImageBitmap(mDefaultBitmap1);
									}

									@Override
									public void onLoadingComplete(
											Bitmap loadedImage) {
										if (loadedImage == null) {
											holder.imageView.setImageBitmap(mDefaultBitmap2);
										}
									}

									@Override
									public void onLoadingCancelled() {
									}
								});
					} else {
						mImageLoader.displayImage(url, holder.imageView,
								mDisplayImageOptions_One,
								new ImageLoadingListener() {
									@Override
									public void onLoadingStarted() {
									}

									@Override
									public void onLoadingFailed(
											FailReason failReason) {
										holder.imageView.setImageBitmap(mDefaultBitmap2);
									}

									@Override
									public void onLoadingComplete(
											Bitmap loadedImage) {
										if (loadedImage == null) {
											holder.imageView.setImageBitmap(mDefaultBitmap1);
										}
									}

									@Override
									public void onLoadingCancelled() {
									}
								});
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return convertView;
		}

		public void setColor(TextView textView, int position) {
			int color;
			switch (position % 3) {
			case 0:
				color = getResources().getColor(R.color.news_1);
				break;
			case 1:
				color = getResources().getColor(R.color.news_2);
				break;
			case 2:
				color = getResources().getColor(R.color.news_3);
				break;
			case 3:
				color = getResources().getColor(R.color.news_4);
				break;
			default:
				color = getResources().getColor(R.color.news_2);
				break;
			}
			textView.setBackgroundColor(color);
		}
	}

	static class ViewHolder {
		ImageView imageView;
		TextView textView;
	}
}
